package com.example.shop.common.util;

import java.util.concurrent.*;

/**
 * 缓存线程池
 * 创建一些线程保存在内存中，等待被用
 * 当线程超过60秒没有被用，则会被回收失活，即线程会被终结销毁
 * 但是是会至少保持有10个线程永不会被回收
 */
public class CachedThreadPoolUtil {
    private static ThreadPoolExecutor cachedThreadPool = new ThreadPoolExecutor(10,
            Integer.MAX_VALUE,60L,TimeUnit.SECONDS,new SynchronousQueue<Runnable>());

    public static <T> Future<T> submit(Callable<T> task){
        return cachedThreadPool.submit(task);
    }

    public static <T> Future<T> submit(Runnable task, T result){
        return cachedThreadPool.submit(task,result);
    }
    public static Future<?> submit(Runnable task){
        return cachedThreadPool.submit(task);
    }

    public static ThreadPoolExecutor getCachedThreadPool(){
        return cachedThreadPool;
    }

    public static void main(String[] args) {
        System.out.println(CachedThreadPoolUtil.getCachedThreadPool().getPoolSize());
        System.out.println(CachedThreadPoolUtil.getCachedThreadPool().getActiveCount());
        Future<?> submit = CachedThreadPoolUtil.submit(() -> {
            System.out.println("开始");
            Future<?> aaaa = CachedThreadPoolUtil.submit(() -> {
                System.out.println("aaaa");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("bbbbb");
                return "aa";
            });
            try {
                Object o = aaaa.get();
                System.out.println(o);
                System.out.println(aaaa.isDone());
                System.out.println(CachedThreadPoolUtil.getCachedThreadPool().getPoolSize());
                System.out.println(CachedThreadPoolUtil.getCachedThreadPool().getActiveCount());
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("结束");
            System.out.println(CachedThreadPoolUtil.getCachedThreadPool().getPoolSize());
            System.out.println(CachedThreadPoolUtil.getCachedThreadPool().getActiveCount());
        });
        while(!submit.isDone()){
        }
        System.out.println("aaaccadadfasdfasfdsafas");
    }

}
